package com.lkl.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lkl.demo.annotation.LoginUser;
import com.lkl.demo.common.result.ResponseEnum;
import com.lkl.demo.entity.Order;
import com.lkl.demo.entity.SeckillOrder;
import com.lkl.demo.entity.User;
import com.lkl.demo.service.IGoodsService;
import com.lkl.demo.service.IOrderService;
import com.lkl.demo.service.ISeckillOrderService;
import com.lkl.demo.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/seckill")
public class SeckillController {

    @Autowired
    private ISeckillOrderService seckillOrderService;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IGoodsService goodsService;

    @PostMapping("/doSeckill")
    public String doKill(@LoginUser User user, Long goodsId, Model model) {
        if (user == null) {
            return "login";
        }

        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);

        if (goodsVo.getStockCount() <= 0) {
            model.addAttribute("errMsg", ResponseEnum.EMPTY_STOCK.getMessage());
            return "secKillFail";
        }

        //判断是否重复抢购 单个用户只能购买同一件商品一次
        SeckillOrder seckillOrder = seckillOrderService.getOne(new
                QueryWrapper<SeckillOrder>()
                .eq("user_id", user.getId())
                .eq("goods_id", goodsVo.getId()));
        if (seckillOrder != null) {
            model.addAttribute("errMsg", ResponseEnum.REPEAT_ERROR.getMessage());
            return "secKillFail";
        }

        Order order = orderService.seckill(user, goodsVo);
        model.addAttribute("order", order);
        model.addAttribute("goods", goodsVo);
        return "orderDetail";
    }
}
